package com.mvd.app.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac2020.VideoListActivity;
import com.mvd.app.ac2021.activitys.Wai_6M_PhotoActivity;
import com.mvd.app.adapter.ContentAdapter2;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.buhege.BuWaiJianResultActivity;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.JsonUtil;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.SystemUtil;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.OtherWaiJianPhotoModel;
import com.mvd.app.model.OutPhotoItem;
import com.mvd.app.model.RecheckCarsModel;
import com.mvd.app.model.StationInforModel;
import com.mvd.app.model.TypeModel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.mvd.app.application.BaseApplication.WAIJIAN_PHOTO_PREVIEW_LISTS;

/**
 * 复检拍照
 */

public class ReCheckTakePhotoActivity extends TakePhotoActivity implements AdapterView.OnItemClickListener, ApiConfig {
    @BindView(R.id.ac_recheck_photo_listview)
    ListView acRecheckPhotoListview;
    @BindView(R.id.ac_recheck_photo_btn_wancheng2)
    Button acRecheckPhotoBtnWancheng2;
    @BindView(R.id.ac_recheck_photo_ll_bottom_layout)
    LinearLayout acRecheckPhotoLlBottomLayout;
    @BindView(R.id.ac_recheck_photo_scrollview)
    ScrollView acRecheckPhotoScrollview;
    @BindView(R.id.title_btn_left)
    ImageButton titleBtnLeft;
    @BindView(R.id.title_btn_left_txt)
    Button titleBtnLeftTxt;
    @BindView(R.id.title_txt)
    TextView titleTxt;
    @BindView(R.id.iv_headtip)
    ImageView ivHeadtip;
    @BindView(R.id.title_btn_right_txt)
    Button titleBtnRightTxt;
    @BindView(R.id.title_btn_right)
    ImageButton titleBtnRight;
    @BindView(R.id.ac_recheck_photo_btn_6m)
    Button acRecheckPhotoBtn6m;
    @BindView(R.id.ac_recheck_photo_btn_vin_shipin)
    Button acRecheckPhotoBtnVinShipin;
    @BindView(R.id.ac_recheck_photo_btn_haerbin)
    Button acRecheckPhotoBtnHaerbin;
    @BindView(R.id.ac_recheck_photo_btn_buhgege)
    Button acRecheckPhotoBtnBuhgege;
//    @BindView(R.id.ac_recheck_2_times)
//    EditText acRecheck2Times;

    private ReCheckTakePhotoActivity instances = null;
    private RecheckCarsModel recheckCarsModel;
    private List<TypeModel> typeModelList;
    private List<TypeModel> typeModelListAdapter;
    private ContentAdapter2 contentAdapter2;
    private String Login_name = "", login_IDNumber;//当前登录的检测员的名字


    static final String STATE_PHOTO_TYPE = "PHOTO_TYPE";
    static final String STATE_PHOTO_TYPE_huan = "PHOTO_TYPE_huan";
    static final String STATE_typeModel = "typeModel";
    static final String STATE_TypeModel_Position = "TypeModel_Position";

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // 保存用户自定义的状态
        savedInstanceState.putString(STATE_PHOTO_TYPE, PHOTO_TYPE);
        savedInstanceState.putSerializable(STATE_typeModel, typeModel);
        savedInstanceState.putInt(STATE_TypeModel_Position, TypeModel_Position);
        // 调用父类交给系统处理，这样系统能保存视图层次结构状态
        super.onSaveInstanceState(savedInstanceState);
    }

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // 总是调用超类，以便它可以恢复视图层次超级
        super.onRestoreInstanceState(savedInstanceState);
        // 从已保存的实例中恢复状态成员
        PHOTO_TYPE = savedInstanceState.getString(STATE_PHOTO_TYPE);
        typeModel = (TypeModel) savedInstanceState.getSerializable(STATE_typeModel);
        TypeModel_Position = savedInstanceState.getInt(STATE_TypeModel_Position);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_recheck);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        ButterKnife.bind(this);
        instances = this;
        setTopTitle("补传照片");
        setBackBtn();
        init();
        WAIJIAN_PHOTO_PREVIEW_LISTS = new HashMap<>();
        login_IDNumber = getIntent().getExtras().getString("login_IDNumber", "");
        Login_name = getIntent().getExtras().getString("Login_name", "");
        recheckCarsModel = (RecheckCarsModel) getIntent().getSerializableExtra("re_model");

//        acRecheck2Times.setText(recheckCarsModel.getTimes());
        UtilsLog.e("补传照片----检测项目=recheckCarsModel=" + recheckCarsModel.toString());
        UtilsLog.e("补传照片----检测项目=getDividerHeight=" + acRecheckPhotoListview.getDividerHeight());
        takePhoto = getTakePhoto();

        String logStrf22 = "\n" + "onCreate-----补传照片----recheckCarsModel---" + "\n"
                + "recheckCarsModel:" + recheckCarsModel.toString() + "\n";
        PDALogUtils.createLogFile(32, logStrf22.getBytes());

        getData(0);

//        //哈尔滨地区--
        if (SharedPreferencesUtils.getHaErBinVersion(instances)) {
            acRecheckPhotoBtnHaerbin.setVisibility(View.GONE);
            getStationInfor();
        } else {
            acRecheckPhotoBtnHaerbin.setVisibility(View.GONE);
        }

        String logStrf3445 = "\n" + "onCreate-----补传照片----哈尔滨地区开关---" + "\n"
                + "SharedPreferencesUtils.getHaErBinVersion(instances):" + SharedPreferencesUtils.getHaErBinVersion(instances) + "\n";
        PDALogUtils.createLogFile(32, logStrf3445.getBytes());
    }

    /**
     * Back按钮退出 activity
     */

    public void setBackBtn() {
        View v = findViewById(R.id.title_btn_left);
        if (v == null)
            return;
        v.setVisibility(View.VISIBLE);
        ((ImageButton) v).setImageResource(R.mipmap.nav_backarrow);
        v.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 设置标题(int：从配置里读取，String：直接赋值)
     */
    public void setTopTitle(Object str) {
        View v = findViewById(R.id.title_txt);
        if (v == null)
            return;
        if (str instanceof String) {
            ((TextView) v).setText(String.valueOf(str));
        } else if (str instanceof Integer) {
            ((TextView) v).setText(((Integer) str).intValue());
        }
    }

    @OnClick({R.id.ac_recheck_photo_btn_wancheng2,
            R.id.ac_recheck_photo_btn_6m, R.id.ac_recheck_photo_btn_buhgege,
            R.id.ac_recheck_photo_btn_vin_shipin,
            R.id.ac_recheck_photo_btn_haerbin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ac_recheck_photo_btn_haerbin:
                String logStrf3445 = "\n" + "onCreate-----补传照片----哈尔滨地区按钮点击---" + "\n"
                        + "SharedPreferencesUtils.getHaErBinVersion(instances):" + SharedPreferencesUtils.getHaErBinVersion(instances) + "\n";
                PDALogUtils.createLogFile(32, logStrf3445.getBytes());
                if (SharedPreferencesUtils.getHaErBinVersion(instances)) {
                    //哈尔滨地区  跳转第三方拍照
//                    gotoApp();
                    gotoApp2("0111|车辆左前方斜视45度照片,");
                }
                break;
            case R.id.ac_recheck_photo_btn_buhgege:
                //不合格项目录入
                Intent bu = new Intent(this, BuWaiJianResultActivity.class);
                bu.putExtra("model_CarsInforModel", recheckCarsModel);
                bu.putExtra("Car_Line", recheckCarsModel.getLine());
                bu.putExtra("login_w_name", Login_name);
                bu.putExtra("login_IDNumber", login_IDNumber);
                bu.putExtra("flag", 1);
                startActivity(bu);
                break;
            case R.id.ac_recheck_photo_btn_6m:
                Intent i_12 = new Intent(this, Wai_6M_PhotoActivity.class);
                i_12.putExtra("model_CarsInforModel", recheckCarsModel);
                i_12.putExtra("Car_Line", recheckCarsModel.getLine());
                i_12.putExtra("login_w_name", Login_name);
                i_12.putExtra("login_IDNumber", login_IDNumber);
                i_12.putExtra("flag", 1);
                startActivity(i_12);
                break;
            case R.id.ac_recheck_photo_btn_vin_shipin:
                Intent intent_video_1 = new Intent(instances, VideoListActivity.class);
//                Intent intent_video_1 = new Intent(instances, BuChuanVideoListActivity.class);
                intent_video_1.putExtra("CarDetailsActivity_CarsInforModel", recheckCarsModel);
                intent_video_1.putExtra("CarDetailsActivity_acCarDetailsWaijianchedao", recheckCarsModel.getLine());
                intent_video_1.putExtra("video_type", 1);
                intent_video_1.putExtra("flag", 1);
                intent_video_1.putExtra("CarDetailsActivity_Line", recheckCarsModel.getLine());
                startActivity(intent_video_1);
                break;
            case R.id.ac_recheck_photo_btn_wancheng2:
                //其他拍照照片
                String logStr3 = "\n" + "外检-复检拍照--其他拍照照片按钮点击" + "\n";
                PDALogUtils.createLogFile(32, logStr3.getBytes());
                Intent intent_3 = new Intent(instances, OtherWaiJianPhotoActivity.class);
                startActivityForResult(intent_3, 404);
                break;
        }
    }

    private void getData(int type) {
        if (CommonUtils.isOnline(this)) {
            if (type == 0) {
                getOutPhotoItem();
            }
        } else {
            Toast.makeText(this, getResources().getString(R.string.network_error), Toast.LENGTH_LONG)
                    .show();
        }
    }


    private void init() {
        typeModelList = new ArrayList<>();
        typeModelListAdapter = new ArrayList<>();
    }

    //获取某辆车的外检拍照的项目
    // PlateType,CarType,Usage
    private void getOutPhotoItem() {
        OutPhotoItem model = new OutPhotoItem();
        model.setCarType(recheckCarsModel.getType());
        model.setPlateType(recheckCarsModel.getPlateType());
        model.setUsage(recheckCarsModel.getUsage());
        model.setPlatformSN(recheckCarsModel.getPlatformSN());
        Gson gson = new Gson();
        String json_str = gson.toJson(model);
        String logStrf22 = "\n" + "-----补传照片---getOutPhotoItem--json" + "\n" + "json:" + json_str + "\n" + "url:" + SharedPreferencesUtils.getIP(this) + WAI_JIAN_PHOTO_ITEM + "\n";
        PDALogUtils.createLogFile(32, logStrf22.getBytes());
        UtilsLog.e("getOutPhotoItem---json_str==" + json_str);
        UtilsLog.e("getOutPhotoItem---url==" + SharedPreferencesUtils.getIP(this) + WAI_JIAN_PHOTO_ITEM);
        OkGo.<String>post(SharedPreferencesUtils.getIP(this) + WAI_JIAN_PHOTO_ITEM).tag(this)
                .upJson(json_str)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        String logStrf22 = "\n" + "-----补传照片---getOutPhotoItem--onSuccess" + "\n" + "result:" + result.toString() + "\n";
                        PDALogUtils.createLogFile(32, logStrf22.getBytes());
                        BaseApplication.msg = result;
//                        UtilsLog.e("getOutPhotoItem-result==" + result);
                        CommonUtils.hideLoadingDialog(instances);
                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("getOutPhotoItem-newResult==" + newResult);
                        if (!TextUtils.isEmpty(newResult) && !"[[]]".equals(newResult) && !"[{}]".equals
                                (newResult) && !"[]".equals(result)) {
                            typeModelList = JsonUtil.stringToArray(newResult,
                                    TypeModel[].class);
                            if (typeModelList != null && typeModelList.size() > 0) {
                                TypeModel typeModel = null;
                                for (int i = 0; i < typeModelList.size(); i++) {
                                    typeModel = new TypeModel();
                                    typeModel.setName(typeModelList.get(i).getName());
                                    typeModel.setCode(typeModelList.get(i).getCode());
                                    typeModelListAdapter.add(typeModel);
                                }
                                if (SharedPreferencesUtils.getHaErBinVersion(instances)) {
                                    up_json_str = "";
                                    for (int i = 0; i < typeModelList.size(); i++) {
                                        up_json_str += typeModelList.get(i).getCode() + "|" +
                                                typeModelList.get(i).getName() + ",";
                                    }
                                    UtilsLog.e("up_json_str==" + up_json_str.substring(0, up_json_str.length() - 1));
                                    String logStr2 = "\n" + "补传照片--外检--哈尔滨跳转拼装json===" +
                                            "\n" + "up_json_str::" + up_json_str.substring(0, up_json_str.length() - 1) + "\n" + "up_json_str::" + up_json_str + "\n";
                                    PDALogUtils.createLogFile(32, logStr2.getBytes());
                                }
                                contentAdapter2 = new ContentAdapter2(instances, typeModelListAdapter,
                                        mListener, instances, 1);
                                acRecheckPhotoListview.setAdapter(contentAdapter2);
                                setListViewHeightBasedONChildren(acRecheckPhotoListview);
//                                Utility.setListViewHeightBasedOnChildren(acRecheckPhotoListview);
//                                acRecheckPhotoListview.setSelection(ListView.FOCUS_DOWN);
                                acRecheckPhotoListview.setOnItemClickListener(instances);
                            }
                        } else {
                            BaseApplication.msg = result;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        BaseApplication.msg = response.body() + "==" + response.message();
                        UtilsLog.e("getOutPhotoItem-onError==" + response.body());
                        CommonUtils.hideLoadingDialog(instances);
                        String logStrf22 = "\n" + "-----补传照片---getOutPhotoItem--onError" + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(32, logStrf22.getBytes());
                    }
                });
    }

    /**
     * 实现类，响应按钮点击事件
     */
    TypeModel typeModel;
    int TypeModel_Position = 0;
    String PHOTO_TYPE = null;//外检拍照的TYPE上传类型
    TakePhoto takePhoto;
    Uri imageUri;
    String tag = "tag";
    // 相册
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;
    private static String picFileFullName;
    private String img_imageUri_path;
    private ContentAdapter2.MyClickListener mListener = new ContentAdapter2.MyClickListener() {
        @Override
        public void myOnClick(int position, View v, int flag) {
            PHOTO_TYPE = typeModelListAdapter.get(position).getCode();
            TypeModel_Position = position;
            String logStrf = "\n" + "-----补传照片-----" + "\n" + "PHOTO_TYPE:" + PHOTO_TYPE + "\n" +
                    "typeModelListAdapter" + typeModelListAdapter.toString() + "\n" +
                    "TypeModel_Position" + TypeModel_Position + "\n";
            PDALogUtils.createLogFile(32, logStrf.getBytes());
            FLAG = flag;
            if (flag == 0) {
                //跳转到图片预览界面
                takePhoto = getTakePhoto();
                File file = new File(Environment.getExternalStorageDirectory(), external_path + "/temp_my_app/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=7777=" + imageUri);
                img_imageUri_path = imageUri.getPath();
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=888=" + imageUri.getPath());
                takePhoto.onPickFromDocuments();
                typeModel = new TypeModel();
                typeModel.setName(typeModelListAdapter.get(position).getName());
                typeModel.setCode(typeModelListAdapter.get(position).getCode());
            } else if (flag == 1) {
//                if (SharedPreferencesUtils.getHaErBinVersion(instances)) {
//                    //哈尔滨拍照typeModelListAdapter
//                    String code = typeModelListAdapter.get(position).getCode() + "|" +
//                            typeModelListAdapter.get(position).getName() + ",";
//                    gotoApp2(code);
//                } else {
                takePhoto = getTakePhoto();
                File file = new File(Environment.getExternalStorageDirectory(), external_path + "/temp_my_app/" + System
                        .currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=7777=" + imageUri);
                img_imageUri_path = imageUri.getPath();
                UtilsLog.e("photo", "WAIJIAN_PHOTO_imageUri=888=" + imageUri.getPath());
                takePhoto.onPickFromCapture(imageUri);
                typeModel = new TypeModel();
                typeModel.setName(typeModelListAdapter.get(position).getName());
                typeModel.setCode(typeModelListAdapter.get(position).getCode());
//                }


            } else {
//                //跳转到图片预览界面
                if (WAIJIAN_PHOTO_PREVIEW_LISTS.get(PHOTO_TYPE) != null) {
                    Intent intent_preview = new Intent(instances, PhotoPreviewActivity.class);
                    intent_preview.putExtra("key_integer", PHOTO_TYPE);
                    startActivity(intent_preview);
                }
            }
        }
    };


    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Log.e("photo", "拍照失败==" + msg);
        ArrayList<TImage> images = result.getImages();
        if (images != null && images.size() > 0) {
            String photo_file_path = images.get(0).getCompressPath();
            String photo_file_path2 = images.get(0).getOriginalPath();
            Log.e("photo", "拍照失败--path==" + photo_file_path);
            Log.e("photo", "拍照失败--path=22=" + photo_file_path2);
        }
    }

    String photo_file_path_OriginalPath;
    int FLAG = 1;//0:拍照   1：相册

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        ArrayList<TImage> images = result.getImages();
        if (images != null && images.size() > 0) {
//            String photo_file_path = images.get(0).getCompressPath();
//            Log.e("photo", "拍照成功--path==" + photo_file_path);
//            File photo_flie = new File(photo_file_path);

            //拍照压缩后上传
//            getData(photo_flie, photo_file_path);
//            photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
//                    .getOriginalPath().replace("my_images/", "");
            if (FLAG == 1) {
                //拍照
                if (SystemUtil.getSystemModel().contains("GIONEE") || SystemUtil.getSystemModel().contains("gionee")) {
                    //金立手机的路线
                    photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
                            .getOriginalPath().replace("my_images/", "").replace(external_path2, "");
                    Log.e("photo", "拍照成功-金立手机-path=22=" + photo_file_path_OriginalPath);
                } else {
                    //其他手机
                    /***
                     * @question 拍照返回的照片的路径处理
                     * @method 有的手机返回的照片带有/storage/emulated/0，
                     * @method 有的不带，所以需要分别处理
                     * @import 找个地方划重点，考试要考的，TDM CD
                     */
                    if (images.get(0).getOriginalPath().contains("storage/emulated")) {
                        photo_file_path_OriginalPath = images.get(0).getOriginalPath().replace("my_images/", "").replace(external_path2, "");
                    } else {
                        photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
                                .getOriginalPath().replace("my_images/", "").replace(external_path2, "");
                    }
//                    photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
//                            .getOriginalPath().replace("my_images/", "");
                    Log.e("photo", "拍照成功--path=22=" + photo_file_path_OriginalPath);
                }
            } else {
                //相册
                photo_file_path_OriginalPath = images.get(0)
                        .getOriginalPath().replace("my_images/", "").replace(external_path2, "");
                Log.e("photo", "相册--path=2234343434=" + photo_file_path_OriginalPath);
            }
            if (!TextUtils.isEmpty(photo_file_path_OriginalPath)) {
//                    Log.e("photo", "拍照成功--path=33=" + img_imageUri_path);
//                if (SharedPreferencesUtils.getPhotoClipping(instances)) {
//                    //拍照需要编辑的
//                    Intent intent = new Intent(instances, WaiRotatePhotoActivity.class);
//                    intent.putExtra("wa_rotate_img", photo_file_path_OriginalPath);
//                    startActivityForResult(intent, 917);
//                } else {
                //拍照不需要编辑的
                Luban.with(instances)
                        .load(new File(photo_file_path_OriginalPath))                     //传人要压缩的图片
                        .setCompressListener(new OnCompressListener() { //设置回调
                            @Override
                            public void onStart() {
                                // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            }

                            @Override
                            public void onSuccess(File file) {
                                // TODO 压缩成功后调用，返回压缩后的图片文件
                                Log.e("photo", "压缩成功后调用");
                                //拍照压缩后上传
//                                    getData(file,picFileFullName);
                                getData(file, photo_file_path_OriginalPath);
                            }

                            @Override
                            public void onError(Throwable e) {
                                // TODO 当压缩过程出现问题时调用
                                Toast.makeText(instances, "图片压缩出现问题，请重试", Toast.LENGTH_LONG).show();
                            }
                        }).launch();    //启动压缩
            }
//            }
        }
    }

    private void getData(File file, String file_name) {
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getIP(instances))) {
            if (CommonUtils.isOnline(instances)) {
                getDataUploadPhoto(file, file_name);
            } else {
                Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
                        .LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "请设置IP与端口号", Toast.LENGTH_LONG).show();
        }
    }


    public static void setListViewHeightBasedONChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + 3 * (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == 404) {
                List<OtherWaiJianPhotoModel> list = (List<OtherWaiJianPhotoModel>) data.getSerializableExtra("othet_waijian_photo");
                if (list != null && list.size() > 0 && typeModelListAdapter != null && typeModelListAdapter.size() >= 0) {
                    String logStrf = "\n" + "-----补传照片----list-" + "\n" + "list:" + list.toString() + "\n";
                    PDALogUtils.createLogFile(32, logStrf.getBytes());
                    //添加新选择的外检拍照
                    TypeModel typeModel = null;
                    for (int j = 0; j < list.size(); j++) {
                        typeModel = new TypeModel();
                        typeModel.setName(list.get(j).getName());
                        typeModel.setCode(list.get(j).getCode());
                        typeModelListAdapter.add(typeModel);
                    }
//                    if (SharedPreferencesUtils.getHaErBinVersion(instances)) {
//                        up_json_str = "";
//                        for (int i = 0; i < list.size(); i++) {
//                            up_json_str += list.get(i).getCode() + "|" +
//                                    list.get(i).getName() + ",";
//                        }
//                        UtilsLog.e("up_json_str==" + up_json_str.substring(0, up_json_str.length() - 1));
//                        String logStr2 = "\n" + "补传照片--外检--哈尔滨跳转拼装json===onActivityResult==" +
//                                "\n" + "up_json_str::" + up_json_str.substring(0, up_json_str.length() - 1) + "\n" + "up_json_str::" + up_json_str + "\n";
//                        PDALogUtils.createLogFile(32, logStr2.getBytes());
//                    }


                    String logStrf22 = "\n" + "-----补传照片----typeModelListAdapter-" + "\n" + "typeModelListAdapter:" + typeModelListAdapter.toString() + "\n";
                    PDALogUtils.createLogFile(32, logStrf22.getBytes());
                    //重新适配listview
                    contentAdapter2 = new ContentAdapter2(instances, typeModelListAdapter,
                            mListener, instances, 1);
                    acRecheckPhotoListview.setAdapter(contentAdapter2);
                    setListViewHeightBasedONChildren(acRecheckPhotoListview);
//                    Utility.setListViewHeightBasedOnChildren(acRecheckPhotoListview);
//                acRecheckPhotoListview.setSelection(ListView.FOCUS_DOWN);
                }
            }
        }
    }


    //上传照片
    private void getDataUploadPhoto(final File file, final String file_name) {
        String IMEI = "";
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getIMEI(this))) {
            IMEI = SharedPreferencesUtils.getIMEI(this);
        } else {
            String str0 = "", str1 = "";
            str0 = CommonUtils.getIMEI(this, 0);
            str1 = CommonUtils.getIMEI(this, 1);
            if (!TextUtils.isEmpty(str0) && str0 != "") {
                IMEI = str0;
            } else {
                IMEI = str1;
            }
        }
        UtilsLog.e("getDataUploadPhoto---url==" + SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO);
        String logStrf = "\n" + "-----补传照片-----getDataUploadPhoto" + "\n" + "PHOTO_TYPE:"
                + PHOTO_TYPE + "\n" +
                "typeModelListAdapter" + typeModelListAdapter.toString() + "\n";
        PDALogUtils.createLogFile(32, logStrf.getBytes());

        String str = "QueueID:" + recheckCarsModel.getQueueID() + "\n" +
                "GUID:" + recheckCarsModel.getGUID() + "\n" +
                "Times:" + recheckCarsModel.getTimes() + "\n" +
                "PlatformSN:" + recheckCarsModel.getPlatformSN() + "\n" +
                "SN:" + recheckCarsModel.getSN() + "\n" +
                "PhotoDate:" + DateUtil.currentTime2() + "\n" +
                "PhotoType:" + PHOTO_TYPE + "\n" +
                "Type:" + recheckCarsModel.getType() + "\n" +
                "CarNO:" + recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO() + "\n" +
                "PlateType:" + recheckCarsModel.getPlateType() + "\n" +
                "ItemCode:" + "F1" + "\n" +
                "Line:" + recheckCarsModel.getLine() + "\n" +
                "VIN:" + recheckCarsModel.getVIN() + "\n" +
                "IMEI:" + IMEI + "\n" +
                "AppearanceInspector:" + Login_name + "\n" +
                "FileType:" + "jpg" + "\n";
        UtilsLog.e("安检getDataUploadPhoto---json==" + str);

        String logStr = "\n" + "补传照片---外检上传照片--getDataUploadPhoto-json==" +
                "\n" + "json::" + str + "\n";
        PDALogUtils.createLogFile(0, logStr.getBytes());
        OkGo.<String>post(SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO).tag(instances)
//                .params("PHOTO_TYPE", PHOTO_TYPE)
                .params("AppearanceInspector", Login_name)
                .params("IMEI", IMEI)
                //guid
                .params("QueueID", recheckCarsModel.getQueueID())
                //guid
                .params("GUID", recheckCarsModel.getGUID())
                //次数
//                .params("Times", acRecheck2Times.getText().toString().trim())
                .params("Times", recheckCarsModel.getTimes())
                //PlatformSN
                .params("PlatformSN", recheckCarsModel.getPlatformSN())
                //SN
                .params("SN", recheckCarsModel.getSN())
                //拍摄时间
                .params("PhotoDate", DateUtil.currentTime2())
                //照片类型-拍的哪里的照片，位置
//                .params("PhotoType", getPlatformCode(PHOTO_TYPE))
                .params("PhotoType", PHOTO_TYPE)

                //车辆类型
                .params("Type", recheckCarsModel.getType())
                //车牌号码，两个拼起来的
                .params("CarNO", recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO())
                //号牌类型
                .params("PlateType", recheckCarsModel.getPlateType())
                //拍照code F1表示外检
                .params("ItemCode", "F1")
                //外检车道，检测线代号
                .params("Line", recheckCarsModel.getLine())
                //车辆识别代码
                .params("VIN", recheckCarsModel.getVIN())
                .params("FileType", "jpg")
//                .params("FileType", FileUtils.getExtensionName(file.getName()))
                //照片
                .params("zp", file)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("getDataUploadPhoto-result==" + result);
//                        UtilsLog.e("response.headers()-result==" + response.headers());
//                        photo_result(PHOTO_TYPE);
//                        if (PHOTO_TYPE != null) {
//                            WAIJIAN_PHOTO_PREVIEW_LISTS.put(Integer.parseInt(PHOTO_TYPE), file);
//                        }

                        String logStr = "\n" + "重新拍照--外检上传照片--onSuccess" +
                                "\n" + "result::" + response.body();
                        PDALogUtils.createLogFile(32, logStr.getBytes());
                        WAIJIAN_PHOTO_PREVIEW_LISTS.put(PHOTO_TYPE, file);
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("getDataUploadPhoto-newResult==" + newResult);

                            if ("ok".equalsIgnoreCase(newResult)) {
                                try {
                                    if (!TextUtils.isEmpty(file_name)) {
                                        CommonUtils.DeleteImage(instances, file_name);
                                    } else {

                                        UtilsLog.e("getDataUploadPhoto==没有获取到即将删除的图片路径");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Toast.makeText(instances, "上传成功", Toast.LENGTH_LONG).show();
                                typeModel.setColor(1);
                                typeModelListAdapter.set(TypeModel_Position, typeModel);
                                contentAdapter2.notifyDataSetChanged();
                            } else {
                                Toast.makeText(instances, "上传失败，请重新拍照", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            UtilsLog.e("getDataUploadPhoto-result==" + "没有数据");
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        String logStr2 = "\n" + "补传照片--外检上传照片--onError" +
                                "\n" + "result" + response.body() + "\n";
                        PDALogUtils.createLogFile(0, logStr2.getBytes());
                        UtilsLog.e("getDataUploadPhoto-onError==" + response.body());
                        UtilsLog.e("getDataUploadPhoto-onError==" + response.getException());
                        CommonUtils.hideLoadingDialog(instances);
                        Toast.makeText(instances, getResources().getString(R.string.services_error), Toast
                                .LENGTH_LONG).show();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        instances = null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }


    /**
     * 获取检测站信息
     */
    private StationInforModel stationInforModel;
    String up_json_str = "";

    private void getStationInfor() {
        UtilsLog.e("getStationInfor---url==" + SharedPreferencesUtils.getIP(instances) + JIAN_CE_ZHAN_INFOR);
        String logStr = "\n" + "补传照片--获取检测站信息----url" + "\n" +
                "URL::" + SharedPreferencesUtils.getIP(instances) + JIAN_CE_ZHAN_INFOR + "\n";
        PDALogUtils.createLogFile(32, logStr.getBytes());
        OkGo.<String>get(SharedPreferencesUtils.getIP(instances) + JIAN_CE_ZHAN_INFOR).tag(instances)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        //完成按钮可点击
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
                        String logStr = "\n" + "补传照片--获取检测站信息----onSuccess" + "\n" +
                                "result::" + result + "\n";
                        PDALogUtils.createLogFile(32, logStr.getBytes());
//                        UtilsLog.e("getStationInfor-result==" + result);
                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("getStationInfor-newResult==" + newResult);

                        String newResult2 = newResult.substring(1, newResult.length() - 1);
                        UtilsLog.e("getStationInfor-newResult2==" + newResult2);

                        stationInforModel = new StationInforModel();
                        stationInforModel = JsonUtil.fromJson(newResult2, StationInforModel.class);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("EndAllItem-onError==" + response.body());
                        String logStr = "\n" + "补传照片--获取检测站信息----onError" + "\n" +
                                "result::" + response.body() + "\n";
                        PDALogUtils.createLogFile(32, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
                    }
                });
    }

    //跳转车管所app,目前只用于哈尔滨地区
    private void gotoApp() {
        String logStr = "\n" + "补传照片--哈尔滨地区--进入跳转方法" + "\n";
        PDALogUtils.createLogFile(32, logStr.getBytes());
        UtilsLog.e("recheck--photo---stationInforModel==" + stationInforModel.toString());
        String packageName = "com.dongma.takephotos.app";
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setComponent(new ComponentName(packageName, packageName + ".RequestAction"));
        intent.putExtra("jczmc", stationInforModel.getName());//检验机构名称
        intent.putExtra("clsbdh", recheckCarsModel.getVIN());//车辆识别代号
//        String[] str=carsInforModel.getPlateTypeName().split("-");
        intent.putExtra("hpzl", recheckCarsModel.getPlateType());//号牌种类
        intent.putExtra("hphm", recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO
                ());//车牌号码
        intent.putExtra("jylsh", recheckCarsModel.getPlatformSN());//查验流水号
        UtilsLog.e("外检-gotoApp-次数==" + recheckCarsModel.getTimes());
        intent.putExtra("jycs", recheckCarsModel.getTimes());//次数
        intent.putExtra("jcxdh", recheckCarsModel.getLine());//检测线代号
        intent.putExtra("jczbh", stationInforModel.getSecurityNO());//检验机构编号
        intent.putExtra("jyxm", "F1");//检验项目
        intent.putExtra("zpgs", up_json_str);
//        intent.putExtra("jkxlh","7E1D09090306170400158BCF86C988C78BCC8F9B818DE7EAFC98A2C7A49D636E");//接口序列号
        UtilsLog.e("recheck--photo---getInterfaceNO==" + stationInforModel.getInterfaceNO());
        intent.putExtra("jkxlh", stationInforModel.getInterfaceNO());
        intent.putExtra("zdbs", CommonUtils.getIMEI(instances));//终端标识
        String logStr4 = "\n" + "外检--哈尔滨地区--gotoApp===" +
                "zpgs==" + up_json_str + "\n" +
                "jczmc==" + stationInforModel.getName() + "\n" + "clsbdh==" + recheckCarsModel.getVIN() + "\n" +
                "hpzl==" + recheckCarsModel.getPlateType() + "\n" + "hphm==" + recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO() + "\n" +
                "jylsh==" + recheckCarsModel.getPlatformSN() + "\n" + "jycs==" + recheckCarsModel.getTimes() + "\n" +
                "jcxdh==" + recheckCarsModel.getLine() + "\n" + "jczbh==" + stationInforModel.getSecurityNO() + "\n" +
                "jyxm==" + "F1" + "\n" + "jkxlh==" + stationInforModel.getInterfaceNO() + "\n" +
                "zdbs==" + CommonUtils.getIMEI(instances) + "\n";
        UtilsLog.e("recheck--photo---logStr4---" + logStr4);
        PDALogUtils.createLogFile(32, logStr4.getBytes());
        startActivityForResult(intent, 20);
    }

    //跳转车管所app,目前只用于哈尔滨地区
    private void gotoApp2(String str) {
        UtilsLog.e("stationInforModel==" + stationInforModel.toString());
        String packageName = "com.dongma.takephotos.app";
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setComponent(new ComponentName(packageName, packageName + ".RequestAction"));
        intent.putExtra("jczmc", stationInforModel.getName());//检验机构名称
        intent.putExtra("clsbdh", recheckCarsModel.getVIN());//车辆识别代号
//        String[] str=carsInforModel.getPlateTypeName().split("-");
        intent.putExtra("hpzl", recheckCarsModel.getPlateType());//号牌种类
        intent.putExtra("hphm", recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO());//车牌号码
        intent.putExtra("jylsh", recheckCarsModel.getPlatformSN());//查验流水号
        UtilsLog.e("外检-gotoApp-次数==" + recheckCarsModel.getTimes());
        intent.putExtra("jycs", String.valueOf(recheckCarsModel.getTimes()));//次数
        intent.putExtra("jcxdh", String.valueOf(recheckCarsModel.getLine()));//检测线代号
        intent.putExtra("jczbh", stationInforModel.getSecurityNO());//检验机构编号
        intent.putExtra("jyxm", "F1");//检验项目
        intent.putExtra("zpgs", str);
//        intent.putExtra("jkxlh","7E1D09090306170400158BCF86C988C78BCC8F9B818DE7EAFC98A2C7A49D636E");//接口序列号
        UtilsLog.e("getInterfaceNO==" + stationInforModel.getInterfaceNO());
        intent.putExtra("jkxlh", stationInforModel.getInterfaceNO());
        intent.putExtra("zdbs", CommonUtils.getIMEI(instances));//终端标识
        String logStr4 = "\n" + "补传照片--哈尔滨地区--gotoApp===" + str + "\n" +
                "jczmc==" + stationInforModel.getName() + "\n" + "clsbdh==" + recheckCarsModel.getVIN() + "\n" +
                "hpzl==" + recheckCarsModel.getPlateType() + "\n" + "hphm==" + recheckCarsModel.getPlateRegion() + recheckCarsModel.getPlateNO() + "\n" +
                "jylsh==" + recheckCarsModel.getPlatformSN() + "\n" + "jycs==" + recheckCarsModel.getTimes() + "\n" +
                "jcxdh==" + recheckCarsModel.getLine() + "\n" + "jczbh==" + stationInforModel.getSecurityNO() + "\n" +
                "jyxm==" + "F1" + "\n" + "jkxlh==" + stationInforModel.getInterfaceNO() + "\n" +
                "zdbs==" + CommonUtils.getIMEI(instances) + "\n" + "zpgs==" + str + "\n";
        UtilsLog.e(logStr4);
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr4.getBytes());
        startActivityForResult(intent, 20);
    }

}
